package club.xinghe.filter;

import club.xinghe.entity.Student;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 说明:学生未登录过滤器：不允许学生未登录就直接访问业务
 *
 * @姚文斌
 * @create 2019-10-09 上午 9:22
 */
@WebFilter("/student/*")
public class StudentNoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
     //写过滤内容
        System.out.println("进入了学生未登录过滤器！");
        //将 servletRequest和servletResponse对象转为request对象和reponse对象
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //得到session域里的student对象
        HttpSession session=request.getSession();
        Student student = (Student) session.getAttribute("student");
        //判断用户是否有登录
        if (student!=null){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else{response.sendRedirect("/login.html");}


    }

    @Override
    public void destroy() {

    }
}
